package cn.com.callback

import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
/**
 *
 * @Title: aipHSTListAllocation
 * @Description:华盛证券 将导入的客户 按指定的人均分分配 --内部接口
 * @author: chieh
 * @date 2021-12-24 16:32:00
 *
 */

public class aipHSTListAllocation implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTListAllocation.class);
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime ;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            long startTime = System.currentTimeMillis();

            // 调用处理信息
            JSONObject inObject = JSONObject.parseObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def batchid = inObject.getString("batchid");//批次id
            
            log.debug("解析信息-" + "batchid: " + batchid);
            if (batchid!=''&&batchid!=null) {
                outData = allocationData(eliteBean,batchid,inObject, dataSourceID);
            }else{
				log.error("处理失败(批次号为空错误)!");
                endTime = System.currentTimeMillis();
                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(批次号为空错误),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
			}

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        log.debug("开户客户信息完成返回结果:" + outData);

        return outData;
    }

    // 处理开发名单任务
    public static String allocationData(EliteBean eliteBean,String batchid,JSONObject inObject, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();

        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createdate = dateformat.format(System.currentTimeMillis());

        // 生成批次号
        String batch_guid = KHUtil.getRandomString(36).toUpperCase();

        // 定义返回对象
        JSONObject resultJson = new JSONObject();

       try {

			//循环捞取当前批次的任务
			def selectmarketing_temporarySQL = "select DISTINCT hsid from marketing_temporary where batch_id='" + batchid + "' order by rand()";
			log.debug("查询分配数量selectmarketing_temporarySQL="+selectmarketing_temporarySQL);

			List selectmarketing_temporaryList = eliteBean.chaxun_sql(selectmarketing_temporarySQL, "dataSource");
			def ListNum = selectmarketing_temporaryList.size();
			log.debug("待分配ListNum=" + ListNum);
			
            JSONArray arrJsonArray = inObject.getJSONArray("data");
            int arrInt = arrJsonArray.size();
            log.debug("接入服务顾问List数量:" + arrInt);
			
			//轮询分配次数
			double number=ListNum*1.0/arrInt;
			log.debug("轮询分配次数number :" + number);
			//轮询次数向下取整
			//int count=Math.ceil(number);
			int count=Math.floor(number);
			
			log.debug("轮询次数取整count :" + count);
			int yscount=ListNum%arrInt;
			log.debug("yscount :" + yscount);
			//根据传入人数循环
            for (int i = 0; i < arrInt; i++) {

                JSONObject arrJson = arrJsonArray.getJSONObject(i);
                //String staffid = KHUtil.FastJsonNull(arrJson.getString("staffid"));//staffid
				String staffid = GetJV(arrJson, "staffid"); //staffid
				log.debug("staffid:"+staffid);
				def getstaffSelectSQL =eliteBean.chaxun_sql("select DEFAULTROLEGROUP,counselor_id from staff where STAFF_ID='" + staffid + "'","dataSource")
				String counselor_id= getstaffSelectSQL.get(0).get("counselor_id");
				String rolegroupid= getstaffSelectSQL.get(0).get("DEFAULTROLEGROUP");
				log.debug("服务顾问id=======：" + counselor_id+"        rolegroupid:"+rolegroupid);
				//根据均分配数轮询
				String[] insertSQL = new String[count];
				int m=0;
				
				for (int j = 0; j < count; j++) {
					//到了总量则跳出
					m =(i*count)+j;
					log.debug("m："+m);
					if(m-yscount==ListNum){
						break;
					}
					Map selectmarketing_temporarySQLMAP = selectmarketing_temporaryList.get(m);
					def hsid = selectmarketing_temporarySQLMAP.get("hsid");
					insertSQL[j]="update marketing_temporary set counselor_id='" + counselor_id + "',staff_id='" + staffid + "',rolegroup_id='" + rolegroupid + "' where hsid=  '" + hsid + "'";
				}
				 // 将数据插入数据库
				log.debug(insertSQL.toString());
				int[] sqlResult = eliteBean.updateBatch(insertSQL, dataSourceID);
				log.debug("提交数据库操作SQL结果:" + sqlResult.toString());

            }
			//余数大于0
			if(yscount>0){
				int n=0;
				for (int k = 0; k < yscount; k++) {
					JSONObject arrJson = arrJsonArray.getJSONObject(k);
					//String staffid = KHUtil.FastJsonNull(arrJson.getString("staffid"));//staffid
					String staffid = GetJV(arrJson, "staffid"); //staffid
					log.debug("staffid:"+staffid);
					def getstaffSelectSQL =eliteBean.chaxun_sql("select DEFAULTROLEGROUP,counselor_id from staff where STAFF_ID='" + staffid + "'","dataSource")
					String counselor_id= getstaffSelectSQL.get(0).get("counselor_id");
					String rolegroupid= getstaffSelectSQL.get(0).get("DEFAULTROLEGROUP");
					log.debug("服务顾问id=======：" + counselor_id+"        rolegroupid:"+rolegroupid);
					
					//取最后求余开始的数量
					n=arrInt*count+k;
					log.debug("n："+n);
					Map selectmarketing_temporarySQLMAP = selectmarketing_temporaryList.get(n);
					def hsid = selectmarketing_temporarySQLMAP.get("hsid");
					eliteBean.update("update marketing_temporary set counselor_id='" + counselor_id + "',staff_id='" + staffid + "',rolegroup_id='" + rolegroupid + "' where hsid=  '" + hsid + "'", dataSourceID);				
				}
				
			}
			
            // 生成处理完成时间
            endTime = System.currentTimeMillis();
			
            // 包装拼接返回JSONObject
            resultJson.put("resultcode", 1);
            resultJson.put("resultmessage", "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
        } catch (Exception e) {
            endTime = System.currentTimeMillis();
            resultJson.put("resultcode", 4);
            resultJson.put("resultmessage", "处理失败:(" + e.getMessage() + ")" + "处理完成,调用问题处理时长(毫秒):" +(endTime -startTime));

        }

        return resultJson.toString();
    }
	
	// 解析Json值
		public static String GetJV(JSONObject inJson, String getKey) {
			String Rev_Value = null;
			try {
				Rev_Value = inJson.getString(getKey);
			} catch (Exception e) {
				try {
					Rev_Value = String.valueOf(inJson.getInt(getKey));
				} catch (Exception e1) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
					} catch (Exception e2) {
						try {
							Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
						} catch (Exception e3) {
							Rev_Value = "";
						}
					}
				}
			} finally {
				if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
					Rev_Value = "";
				} else {
				}
			}
			log.debug("解析-k=" + getKey + " v=" + Rev_Value);
			return Rev_Value;
		}

}
